package com.atguigu.encryption.utils;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.*;


@Slf4j
public class ECDSA {

    // 密钥生成
        public static KeyPair generateKeyPair() {
            try {
                KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
                keyGen.initialize(256); // 使用256位曲线参数
                return keyGen.generateKeyPair();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            return null;
        }

        // 数据签名
        // 私钥和数据进行签名，（得到的签名值作为原始的密文,存入ciphertext，作为签名值1）
        public static byte[] signData(String data, PrivateKey privateKey) {
            try {
                Signature signature = Signature.getInstance("SHA256withECDSA");
                signature.initSign(privateKey);
                signature.update(data.getBytes(StandardCharsets.UTF_8));
                return signature.sign();
            } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
                e.printStackTrace();
            }
            return null;
        }

        //签名验证
        // 公钥和签名值1进行操作（得到此时的签名值2，同时和原始数据进行比较即可）
        public static boolean verifySignature(String data, byte[] signature, PublicKey publicKey) {
            try {
                Signature verifier = Signature.getInstance("SHA256withECDSA");
                verifier.initVerify(publicKey);
                verifier.update(data.getBytes(StandardCharsets.UTF_8));
                return verifier.verify(signature);
            } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
                e.printStackTrace();
            }
            return false;
        }

        public static void main(String[] args) {
            String data = "your_data_to_sign";

            // 生成密钥对
            KeyPair keyPair = generateKeyPair();
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey publicKey = keyPair.getPublic();

            // 签名
            byte[] signature = signData(data, privateKey);

            // 验证签名
            boolean isValid = verifySignature(data, signature, publicKey);

            System.out.println("Signature: " + bytesToHex(signature));
            System.out.println("Is valid: " + isValid);
        }

        public static String bytesToHex(byte[] bytes) {
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        }

}
